import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: () => import('@/views/site/Home.vue')
    },
    {
      path: '/document',
      name: 'document',
      component: () => import('@/views/site/Document.vue')
    },
    {
      path: '/price',
      name: 'price',
      component: () => import('@/views/site/Price.vue')
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/site/Login.vue')
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('@/views/site/Register.vue')
    },
    {
      path: '/console',
      name: 'console',
      component: () => import('@/views/console/Console.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/console/detail',
      name: 'consoleDetail',
      component: () => import('@/views/console/Detail.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/console/create',
      name: 'consoleCreate',
      component: () => import('@/views/console/Create.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/console/update',
      name: 'consoleUpdate',
      component: () => import('@/views/console/Update.vue'),
      meta: { requiresAuth: true }
    }
  ],
})

router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  const token = localStorage.getItem('token')

  // 需要登录的页面
  if (to.meta.requiresAuth) {
    if (!token) {
      next('/login')
      return
    }
  }

  // 已登录用户不能访问登录和注册页面
  if ((to.path === '/login' || to.path === '/register') && token) {
    next('/console')
    return
  }

  next()
})

export default router
